//
//  BluetoothViewController.swift
//  RxSwift_Practice
//
//  Created by 李永彬 on 2020/4/24.
//  Copyright © 2020 李永彬. All rights reserved.
//

import UIKit
import Toast_Swift

class BluetoothViewController: UIViewController {

    var tableView:UITableView?
    var dataSource: Array = [LYDiscovery]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.view.backgroundColor = UIColor.white
        self.setupUI()
        //扫描设备
        self.searchDevice()
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "千米", style: .plain, target: self, action: #selector(setKMUnitsForDevice))
//        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "英里", style: .plain, target: self, action: #selector(setMileUnitsForDevice))
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        do {
            try LYCentral.shared.interruptScan()
        } catch {
            
        }
    }
    
    func setupUI() {
        navigationItem.title = "格局商学"
        self.view.backgroundColor = UIColor.white
        tableView = UITableView(frame: UIScreen.main.bounds, style: UITableView.Style.plain)
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 50, right: 0)
        tableView?.rowHeight = 60
        tableView?.backgroundColor = UIColor.white
        tableView?.sectionFooterHeight = 0.00001
        tableView?.tableFooterView = UIView()
        self.view.addSubview(tableView!)
    }
    
    func searchDevice() {

        LYCentral.shared.scanWithDuration(10.0, updateDuplicates: false, progressHandler: { [weak self] (result) in
            
            print(result)
            self?.dataSource += result
            self?.tableView?.reloadData()
        }, completionHandler: {[weak self] (result, error) in

//            self?.dataSource += result!
//            self?.tableView?.reloadData()
        })
    }
    
    deinit {
        
        
    }
        
    func connectSelectedDevice(_ device: LYDiscovery) {

        UIApplication.shared.keyWindow!.makeToastActivity(.center)
        LYCentral.shared.connect(10.0, remotePeripheral: device.remotePeripheral) { (rePeripheral, error) in

            UIApplication.shared.keyWindow!.hideToastActivity()
            if error == nil {
                self.view.makeToast("蓝牙连接成功")
                
                UIApplication.shared.keyWindow!.makeToast("连接设备成功")
  
                let unitsVC = SetUnitsViewController()
                
                self.navigationController?.pushViewController(unitsVC, animated: true)
            } else {
                self.view.makeToast("蓝牙连接失败")
            }
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
}

extension BluetoothViewController : UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  
        let identifer = "identifer"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifer)
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: identifer)
        }
        cell?.backgroundColor = UIColor.white
        cell?.selectionStyle = UITableViewCell.SelectionStyle.none
        let device: LYDiscovery = self.dataSource[indexPath.row]
        cell?.textLabel?.textColor = UIColor.black
        cell?.textLabel?.text = device.localName
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let device: LYDiscovery = self.dataSource[indexPath.row]

        self.connectSelectedDevice(device)
    }
}

